﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using BNF.HMI.DAL;
using BNF.Utility.TimeAPI;
using DataEngine.ContractModel;
using DataEngine.Communication;


namespace TcpSend
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }       
        
        private void btnWriteData_Click(object sender, EventArgs e)
        {
            Thread myT = new Thread(new ThreadStart(RunTest));
            myT.IsBackground = true;
            myT.Start();
        }

        private void RunTest()
        {
            try
            {
                //while (true)
                {
                    CTAPI myTime = new CTAPI();
                    long myUTime = myTime.GetCurrentTimeAsJavaTime();
                    int ItemCount = 5000;
                    List<Object> myList = new List<Object>();
                    for (int i = 0; i < ItemCount; i++)
                    {
                        DATA_POINT myData = new DATA_POINT();
                        myData.TagID = 2430;
                        myData.TimeStamp = (ulong)(myUTime + i);
                        myData.DataType = (ushort)VarEnum.VT_I4;
                        myData.Quality = (byte)QualityEnum.QUALITY_GOOD;
                        myData.Value = clsSocket.GetVariantFromValue(i);

                        myList.Add(myData);
                    }

                    for (int i = 0; i < ItemCount; i++)
                    {
                        DATA_POINT myData = new DATA_POINT();
                        myData.TagID = 1544;
                        myData.TimeStamp = (ulong)(myUTime + i);
                        myData.DataType = (ushort)VarEnum.VT_BOOL;
                        myData.Quality = (byte)QualityEnum.QUALITY_GOOD;
                        myData.Value = clsSocket.GetVariantFromValue(i % 2);

                        myList.Add(myData);
                    }

                    long endtime = myTime.GetCurrentTimeAsJavaTime();
                    writer.InsertDataSync(10, myList);
                    //listBox1.Items.Add(String.Format("Inserted {0} objects", myList.Count));
                    //Thread.Sleep(5000);

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
           
        }
        DEReader reader;
        DEWriter writer;
        DataTable myTab;
        private void Form1_Load(object sender, EventArgs e)
        {
            dtPicker.Value = DateTime.Now;
            txtMinisec.Text = dtPicker.Value.Millisecond.ToString();
            dtPicker.Value=dtPicker.Value.AddMilliseconds(dtPicker.Value.Millisecond * (-1));
            btnConnect_Click(null, null);
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //ns.Close();
            //tcpClient.Close();
          
        }
        private void btnReadData_Click(object sender, EventArgs e)
        {
            CTAPI myTimeLib = new CTAPI();


            UInt32 resolution = String.IsNullOrEmpty(txtResolution.Text) ? 0 : Convert.ToUInt32(txtResolution.Text);
            UInt32 duration = String.IsNullOrEmpty(txtDuration.Text) ? 0 : Convert.ToUInt32(txtDuration.Text);
            UInt64 endtime = 0;
    
            if (!chkRealTime.Checked)
            { 
                if (!chkJavaTime.Checked)
                {
                    endtime = Convert.ToUInt64(myTimeLib.DateTimeToJavaTime(dtPicker.Value) + Convert.ToInt64(txtMinisec.Text));//FirstIndex = 1345543868883
                    txtTimeStamp.Text = endtime.ToString();
                }
                else
                {
                    endtime = Convert.ToUInt64(txtTimeStamp.Text);
                    dtPicker.Value = myTimeLib.JavaTimeToDateTime((long)endtime);
                    txtMinisec.Text = endtime.ToString().Substring(endtime.ToString().Length - 3, 3);
                    dtPicker.Value = dtPicker.Value.AddMilliseconds(Convert.ToDouble(txtMinisec.Text) * (-1));   
                }

            }
            else
            {
                endtime = 0;
            }

            List<UInt32> myDataList = new List<UInt32>();
            myDataList.Add(2430);
            myDataList.Add(1544);

            if(myTab!=null && myTab.Rows.Count>0) myTab.Clear();
            myTab = null;


            listBox1.Items.Add(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff") + String.Format(" ====>Requested [{0}] Tags", myDataList.Count));
            if (chkTrend.Checked)
            {
                myTab = reader.GetTrendSync(10, myDataList, endtime, duration, resolution);
            }
            else
            {
                myTab = reader.GetDataSync(10, myDataList, endtime, duration, resolution);
            }
          
            //=============================================================
            long timestamp = 0;
            if (myTab!=null && myTab.Rows.Count > 0)
            {
                listBox1.Items.Add(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff") + String.Format(" ====>Received [{0}] objects", myTab.Rows.Count));
             
                dataGridView1.DataSource = myTab;
                dataGridView1.AutoResizeColumns();
                if (chkRealTime.Checked && !chkTrend.Checked && !chkJavaTime.Checked)
                {
                    timestamp =Convert.ToInt64(myTab.Rows[myTab.Rows.Count - 1]["TimeStampNum"]);
                    dtPicker.Value = myTimeLib.JavaTimeToDateTime(timestamp);
                    txtMinisec.Text = timestamp.ToString().Substring(timestamp.ToString().Length - 3, 3);
                    dtPicker.Value = dtPicker.Value.AddMilliseconds(Convert.ToDouble(txtMinisec.Text) * (-1));
                    txtTimeStamp.Text = timestamp.ToString(); 
                }

                
            }
            else
            {
                listBox1.Items.Add(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff") + " NO DATA");
            }
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            if (myTab != null && myTab.Rows.Count > 0) myTab.Clear();
            myTab = null;
        }

        private void chkJavaTime_CheckedChanged(object sender, EventArgs e)
        {

            dtPicker.Enabled = !chkJavaTime.Checked;
            txtMinisec.ReadOnly = chkJavaTime.Checked;
            txtTimeStamp.ReadOnly = !chkJavaTime.Checked;
            
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (reader != null) reader.DisConnect();
            reader = new DEReader();
            reader.Connect();

            if (writer != null) writer.DisConnect();
            writer = new DEWriter();
            writer.Connect();
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            reader.DisConnect();
            reader = null;
            writer.DisConnect();
            writer = null;
        }
     
    }
}

